package com.baitengsoft.patentapimonitor.api.service.impl;

import com.baitengsoft.patentapimonitor.api.dao.WebUserDao;
import com.baitengsoft.patentapimonitor.api.entity.*;
import com.baitengsoft.patentapimonitor.api.model.MenuModel;
import com.baitengsoft.patentapimonitor.api.model.MenuViewModel;
import com.baitengsoft.patentapimonitor.api.model.WebUserMenuModel;
import com.baitengsoft.patentapimonitor.api.service.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by Admin on 2017/12/19.
 */
@Service
public class WebRolesmenuRlatServiceImpl extends BaseServiceImpl<WebRolesmenuRlatEntity> implements WebRolesmenuRlatService {

    @Autowired
    private WebRolesService webRolesService;
    @Autowired
    private WebMenuService webmenuservice;
    @Autowired
    private WebPlatformService webPlatformService;
    @Autowired
    private WebUserMenuService webUserMenuService;

    @Autowired
    private WebUserDao webUserDao;

    @Override
    public List<WebRolesmenuRlatEntity> searchByRolesID(int rolesID) {

        try {
            WebRolesmenuRlatEntity webrolesmenurlatentity = new WebRolesmenuRlatEntity();
            webrolesmenurlatentity.setRolesid(rolesID);
            List<WebRolesmenuRlatEntity> entities = queryListByWhere(webrolesmenurlatentity);
            return entities;
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    @Transactional
    public Integer saveRolesMenuRlat(String rolesName, String idStr, String id, int userId) {

        if (StringUtils.isBlank(id)) {//新增
            Integer rolesSuccessId = webRolesService.saveRoles(rolesName, userId);
            if (rolesSuccessId == 0) {//保存失败
                return 0;
            }
            if (StringUtils.isNotBlank(idStr)) {
                String[] ids = idStr.split(",");
                for (String idEvery : ids) {
                    WebRolesmenuRlatEntity entity = new WebRolesmenuRlatEntity();
                    entity.setRolesid(rolesSuccessId);
                    entity.setMenuid(Integer.parseInt(idEvery));
                    Integer successId = saveByNotNull(entity);
                    if (successId == 0) {//保存失败
                        return 0;
                    }
                }
            }
            return 1;//保存成功
        } else {
            //编辑
            Integer editSuccessId = webRolesService.updateById(Integer.parseInt(id), rolesName, userId);
            if (editSuccessId == 0) return editSuccessId;//更新失败
            //样式的菜单添加了就不能修改了，所以这里暂时注释掉
            //先删除,在添加
//            WebRolesmenuRlatEntity entity = new WebRolesmenuRlatEntity();
//            entity.setRolesid(Integer.parseInt(id));
//            List<WebRolesmenuRlatEntity> entities = queryListByWhere(entity);
//            if (entities != null && entities.size() > 0) {//更新删除
//                List<Object> ids = new ArrayList<>();
//                for (WebRolesmenuRlatEntity entityEvery : entities) {
//                    ids.add(entityEvery.getId());
//                }
//                Integer delId = deleteByIds(ids, "id", WebRolesmenuRlatEntity.class);
//                if (delId == 0) return 0;//删除失败
//            }
//
//            if (StringUtils.isNotBlank(idStr)) {//更新添加
//                String[] ids = idStr.split(",");
//                for (String idEvery : ids) {
//                    WebRolesmenuRlatEntity webrolesmenurlatentity = new WebRolesmenuRlatEntity();
//                    webrolesmenurlatentity.setRolesid(Integer.parseInt(id));
//                    webrolesmenurlatentity.setMenuid(Integer.parseInt(idEvery));
//                    Integer successId = saveByNotNull(webrolesmenurlatentity);
//                    if (successId == 0) {//保存失败
//                        return 0;
//                    }
//                }
//            }

            //同步更新用户菜单表

            //获取关联样式用户
             /* List<WebUserinfoEntity> userinfoEntityList = webUserDao.queryByRoleId(Integer.parseInt(id));
                List<String> rolesMenuList=Arrays.asList(idStr.split(","));
                if (userinfoEntityList != null && userinfoEntityList.size() > 0) {
                    for (WebUserinfoEntity userinfoEntity : userinfoEntityList) {
                        List<WebUsermenuEntity> userMenuModelList = webUserMenuService.searchByUserId(userinfoEntity.getId());
                        //List<Integer> menuList= userMenuModelList.stream().map(x->x.getMenuid()).collect(Collectors.toList());
                        //如果role表里对应的menu删除了，对应用户表也要删除，新添加的不用考虑
                        userMenuModelList.forEach(x->{
                            if(rolesMenuList.contains(x.getMenuid().toString())==false){
                                webUserMenuService.deleteByIds(Arrays.asList(x.getId()),"id",WebUsermenuEntity.class);
                            }
                        });
                    }

                }*/

            return 1;
        }


    }

    @Override
    @Transactional
    public Map<String, Object> delRolesMenuRlat(String ids, int userId) {
        Map<String, Object> map = new HashMap<>();
        if (StringUtils.isNotBlank(ids)) {
            String[] idArray = ids.split(",");
            //删除样式之前先去检查该样式是否正在被平台使用
            String rolesName = "";
            for (String platformRolesId : idArray) {
                List<WebPlatformEntity> webPlatformEntities = webPlatformService.searchByRolesId(Integer.parseInt(platformRolesId));
                if (webPlatformEntities != null) {
                    rolesName += webRolesService.searchById(platformRolesId).getName() + ",";
                    map.put("num", -1);
                    map.put("rolesName", rolesName.substring(0, rolesName.length() - 1));
                }
            }
            if (!rolesName.equals("")) return map;


            Integer rolesSuccessId = webRolesService.delRolesById(ids, userId);//删除样式栏目表中数据
            if (rolesSuccessId == 0) {
                map.put("num", 0);//删除失败
                return map;
            }
            WebRolesmenuRlatEntity entity = new WebRolesmenuRlatEntity();
//            if(entity==null){
//                map.put("num",1);
//                return map;
//            }
            for (String rolesId : idArray) {
                List<WebRolesmenuRlatEntity> ren = searchByRolesID(Integer.parseInt(rolesId));
                if (ren != null && ren.size() > 0) {
                    entity.setRolesid(Integer.parseInt(rolesId));
                    Integer delSuccessId = deleteByWhere(entity);
                    if (delSuccessId == 0) {
                        map.put("num", 0);//删除失败
                        return map;
                    }
                }
            }

            map.put("num", 1);
            return map;
        }
        map.put("num", 0);
        return map;
    }

    @Override
    public MenuViewModel searchModelByRolesId(String id) {

        WebRolesEntity rolesEntity = webRolesService.searchById(id);
        if (rolesEntity == null) return null;

        MenuViewModel viewModel = new MenuViewModel();
        List<MenuModel> menuModels = webmenuservice.search();
        List<WebRolesmenuRlatEntity> webRolesmenuRlatEntities = searchByRolesID(rolesEntity.getId());
        if (webRolesmenuRlatEntities != null && webRolesmenuRlatEntities.size() > 0) {
            for (WebRolesmenuRlatEntity webrolesmenurlatentity : webRolesmenuRlatEntities) {
                for (MenuModel menuModel : menuModels) {
                    if (webrolesmenurlatentity.getMenuid() == menuModel.getId()) {
                        menuModel.setIsChecked(true);
                    }
                }
            }
        }
        viewModel.setRolesName(rolesEntity.getName());
        viewModel.setMenus(menuModels);
        return viewModel;
    }
}
